package com.sikaryofficial.backend.service.useraction;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.sikaryofficial.backend.config.TenantFilterProperties;
import com.sikaryofficial.backend.constant.ActivityStatusEnum;
import com.sikaryofficial.backend.constant.ArticleAuditStatusEnum;
import com.sikaryofficial.backend.constant.MyStatisticsTypeEnum;
import com.sikaryofficial.backend.constant.RedisCacheKey;
import com.sikaryofficial.backend.constant.UserActionTypeEnum;
import com.sikaryofficial.backend.domain.dto.req.UserActionReq;
import com.sikaryofficial.backend.domain.dto.resp.BrandTasteEvaluateDTO;
import com.sikaryofficial.backend.domain.dto.resp.UserActionListResp;
import com.sikaryofficial.backend.domain.dto.resp.collection.UserActionActivityResp;
import com.sikaryofficial.backend.domain.dto.resp.collection.UserActionArticleResp;
import com.sikaryofficial.backend.domain.dto.resp.collection.UserActionEvaluateResp;
import com.sikaryofficial.backend.domain.dto.resp.collection.UserActionProductResp;
import com.sikaryofficial.backend.domain.dto.resp.collection.UserActionStoreResp;
import com.sikaryofficial.backend.domain.entity.Activity;
import com.sikaryofficial.backend.domain.entity.ActivityReserve;
import com.sikaryofficial.backend.domain.entity.ActivityResult;
import com.sikaryofficial.backend.domain.entity.BrandTasteEvaluate;
import com.sikaryofficial.backend.domain.entity.Store;
import com.sikaryofficial.backend.domain.entity.UserAction;
import com.sikaryofficial.backend.domain.mapping.BrandTasteEvaluateMapping;
import com.sikaryofficial.backend.domain.mapping.UserActionMapping;
import com.sikaryofficial.backend.domain.vo.ObjectCount;
import com.sikaryofficial.backend.manager.information.ArticleActionDataManager;
import com.sikaryofficial.backend.service.IActivityReserveService;
import com.sikaryofficial.backend.service.IActivityResultService;
import com.sikaryofficial.backend.service.IActivityService;
import com.sikaryofficial.backend.service.IArticleService;
import com.sikaryofficial.backend.service.IAttachmentService;
import com.sikaryofficial.backend.service.IBrandTasteEvaluateService;
import com.sikaryofficial.backend.service.IMyStatisticsService;
import com.sikaryofficial.backend.service.IStoreService;
import com.sikaryofficial.backend.service.IUserActionService;
import com.sikaryofficial.backend.service.IUserActionStrategy;
import com.sikaryofficial.backend.service.address.AddressCacheService;
import com.sikaryofficial.backend.service.article.cache.ReceivedLikesCacheService;
import com.sikaryofficial.backend.service.brand.cache.BrandTasteCacheService;
import com.sikaryofficial.backend.service.statistics.MyStatisticsProcessor;
import com.sikaryofficial.backend.service.statistics.MyStatisticsEvent;
import com.sikaryofficial.backend.service.store.StoreCacheService;
import com.sikaryofficial.backend.service.user.UserCacheService;
import com.sikaryofficial.backend.service.useraction.cache.UserActionCacheService;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.RemoteArticleService;
import com.sikaryofficial.system.api.model.AddressDTO;
import com.sikaryofficial.system.api.model.att.AttachmentResp;
import com.sikaryofficial.system.api.model.infomation.ArticleDTO;
import com.sikaryofficial.system.api.model.product.BrandTasteDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : qinjinyuan
 * @desc : 用户行动抽象
 * @date : 2023/11/02 15:41
 */
@Component
@Slf4j
public abstract class AbstractUserActionStrategyService implements IUserActionStrategy {
    @Autowired
    private IAttachmentService attachmentService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IUserActionService userActionService;
    @Autowired
    private MyStatisticsProcessor myListener;
    @Autowired
    private RedisService redisService;
    @Autowired
    private BrandTasteCacheService brandTasteCacheService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IBrandTasteEvaluateService evaluateService;
    @Autowired
    private AddressCacheService addressCacheService;
    @Autowired
    private IMyStatisticsService myStatisticsService;
    @Autowired
    private UserCacheService userCacheService;
    @Autowired
    private StoreCacheService storeCacheService;
    @Autowired
    private IActivityReserveService reserveService;
    @Autowired
    private UserActionCacheService userActionCacheService;
    @Autowired
    private IActivityResultService activityResultService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private RemoteArticleService remoteArticleService;
    @Autowired
    private ReceivedLikesCacheService receivedLikesCacheService;
    @Autowired
    private ArticleActionDataManager articleActionDataManager;
    @Autowired
    private TenantFilterProperties tenantFilterProperties;

    private void beforeCheckData(UserActionReq req) {
        // 文章相关行为
        boolean flag = !MyStatisticsTypeEnum.LIKES_ARTICLE.getBusinessType().equals(req.getBusinessType())
                && !MyStatisticsTypeEnum.FORWARD_ARTICLE.getBusinessType().equals(req.getBusinessType())
                && !MyStatisticsTypeEnum.COLLECTION_ARTICLE.getBusinessType().equals(req.getBusinessType());
        if (flag) {
            return;
        }
        R<ArticleDTO> sourceR = remoteArticleService.getSimpleInfo(req.getObjectId());
        if (Objects.isNull(sourceR) || Objects.isNull(sourceR.getData())) {
            throw new ServiceException("the article is empty");
        }
        ArticleDTO source = sourceR.getData();
        if (!ArticleAuditStatusEnum.APPROVED.getCode().equals(source.getAuditStatus())) {
            throw new ServiceException("like | forward | collection only at the pass status article");
        }
        // 入参设置文章作者
        req.setAuthorId(source.getCreatedBy());
        // 添加点赞缓存
        receivedLikesCacheService.updateReceivedLikes(req.getBusinessType(), source.getCreatedBy(), req.isOptions());
    }

    /**
     * 前置处理
     *
     * @param req
     */
    @Override
    public void before(UserActionReq req) {
        // 检测数据 && 获取 目标的创建人 && 更新文章点赞缓存
        beforeCheckData(req);
        UserActionTypeEnum userActionTypeEnum = UserActionTypeEnum.getByCode(req.getActionType());
        boolean result = Arrays.stream(userActionTypeEnum.getBusinessTypes()).anyMatch(item -> item.equals(req.getBusinessType()));
        if (!result) {
            throw new ServiceException(MessageFormat.format("actionType: {0}, does not support business {1}, supported business is {2}", req.getActionType(), req.getBusinessType()
                    , Arrays.toString(userActionTypeEnum.getBusinessTypes())));
        }
    }

    /**
     * 处理统计
     *
     * @param myStatisticsEvent
     * @param options           操作 新增 false  取消true
     */
    @Override
    public void processMyStatisticsEvent(MyStatisticsEvent myStatisticsEvent, boolean options) {
        if (options) {
            myListener.reduceMyStatistics(myStatisticsEvent);
        } else {
            myListener.addMyStatistics(myStatisticsEvent);
        }
    }

    /**
     * 保存用户行为
     *
     * @param req
     */
    public void saveUserAction(UserActionReq req) {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();
        // 添加个人行为缓存
        userActionCacheService.saveOwnerAction(userId, req.getObjectId(), req.getBusinessType(), req.isOptions());

        UserAction queryUserAction = userActionService.getOne(new LambdaQueryWrapper<UserAction>()
                .eq(UserAction::getBusinessType, req.getBusinessType())
                .eq(UserAction::getCreatedBy, userId)
                .eq(UserAction::getActionType, req.getActionType())
                .eq(UserAction::getObjectId, req.getObjectId())
                .eq(UserAction::getDeletedVersion, 0L)
                .last(" limit 1")
        );

        // 新增
        if (Objects.isNull(queryUserAction) && !req.isOptions()) {
            UserAction userAction = UserActionMapping.INSTANCE.coverToEntity(req);
            userAction.setUserActionId(IdWorker.getId())
                    .setCreatedBy(userId)
                    .setCreatedName(userName)
                    .setAuthorId(req.getAuthorId())
                    .setCreatedTime(new Date());
            userActionService.save(userAction);
        }
        // 更新
        if (req.isOptions()) {
            Optional.ofNullable(queryUserAction).ifPresent(userAction -> userActionService.update(
                    new LambdaUpdateWrapper<UserAction>()
                            .eq(UserAction::getUserActionId, userAction.getUserActionId())
                            .set(UserAction::getUpdatedBy, userId)
                            .set(UserAction::getUpdatedTime, new Date())
                            .set(UserAction::getDeletedVersion, userAction.getUserActionId())
            ));
        }
    }

    /**
     * 触发缓存清楚
     *
     * @param userId
     * @return
     */

    public void cleanCache(Long userId) {
        redisService.deleteObject(MessageFormat.format(RedisCacheKey.MY_STATISTICS_CACHE, userId));
    }

    /**
     * 构建产品的点赞统计及个人点赞数据
     *
     * @param result
     * @return
     */
    private void buildProductLikesData(List<BrandTasteDTO> result) {
        if (CollUtil.isEmpty(result)) {
            return;
        }
        // 是否点赞、收藏设置
        result.forEach(item -> {
            if (Objects.nonNull(item.getLikesCount()) && item.getLikesCount() > 0) {
                item.setHasOwnerLikes(userActionCacheService.getOwnerAction(SecurityUtils.getUserId(), item.getBrandTasteId(),
                        MyStatisticsTypeEnum.LIKES_PRODUCT_NUM.getBusinessType()));
            }
            if (Objects.nonNull(item.getCollectionCount()) && item.getCollectionCount() > 0) {
                item.setHasOwnerCollection(userActionCacheService.getOwnerAction(SecurityUtils.getUserId(), item.getBrandTasteId(),
                        MyStatisticsTypeEnum.COLLECTION_PRODUCT_NUM.getBusinessType()));
            }
        });
    }

    /**
     * 构建评价的点赞统计及个人点赞数据
     *
     * @param result
     */
    private void buildEvaluateLikesData(List<BrandTasteEvaluateDTO> result) {
        if (CollUtil.isEmpty(result)) {
            return;
        }
        // 填充每条跟评对应的点赞数量
        Optional.of(result).ifPresent(list -> {
            List<ObjectCount> objectCountList = myStatisticsService.countByObjectIds(list.stream().map(BrandTasteEvaluateDTO::getEvaluateId).collect(Collectors.toList()));
            Optional.ofNullable(objectCountList).ifPresent(list1 -> list1.forEach(item -> {
                BrandTasteEvaluateDTO evaluateDTO = result.stream().filter(replyItem -> replyItem.getEvaluateId().equals(item.getObjectId())).findFirst().orElse(null);
                if (Objects.nonNull(evaluateDTO) && MyStatisticsTypeEnum.LIKES_PRODUCT_EVALUATE_NUM.getBusinessType().equals(item.getBusinessType())) {
                    evaluateDTO.setLikesCount(item.getObjectCount());
                }
                if (Objects.nonNull(evaluateDTO) && MyStatisticsTypeEnum.COMMENTS_EVALUATE_REPLAY_NUM.getBusinessType().equals(item.getBusinessType())) {
                    evaluateDTO.setReplyCount(item.getObjectCount());
                }
            }));
        });
        // 是否点赞设置
        result.forEach(evaluateDTO -> {
            if (Objects.nonNull(evaluateDTO.getLikesCount()) && evaluateDTO.getLikesCount() > 0) {
                evaluateDTO.setHasOwnerLikes(userActionCacheService.getOwnerAction(SecurityUtils.getUserId(), evaluateDTO.getEvaluateId(),
                        MyStatisticsTypeEnum.LIKES_PRODUCT_EVALUATE_NUM.getBusinessType()));
            }
        });
    }

    public IPage<UserActionProductResp> getActionWithProduct(IPage<UserAction> userActionPage, Set<Long> objIds) {
        IPage<UserActionProductResp> userActionStoreRespPage = userActionPage.convert(UserActionMapping.INSTANCE::coverToProductResp);
        // 查询产品数据
        List<BrandTasteDTO> brandTastes = brandTasteCacheService.getBrandTasteList(new ArrayList<>(objIds));
        if (CollUtil.isEmpty(brandTastes)) {
            return userActionStoreRespPage;
        }
        // 查询产品点赞数据
        buildProductLikesData(brandTastes);
        // 个人评价产品头像
        Map<Long, String> userAvatarMap = userCacheService.getMultiUserAvatar(brandTastes.stream().map(BrandTasteDTO::getCreatedBy).collect(Collectors.toList()));
        // 填充昵称
        Map<Long, String> userNickNameMap = userCacheService.getMultiUserNickName(brandTastes.stream().map(BrandTasteDTO::getCreatedBy).collect(Collectors.toList()));
        userActionStoreRespPage.getRecords().forEach(userAction -> {
            Optional.ofNullable(brandTastes.stream().filter(store1 -> store1.getBrandTasteId().equals(userAction.getObjectId())).findFirst().orElse(null))
                    .ifPresent(brandTasteDTO -> {
                        userAction.setCreatedName(brandTasteDTO.getCreatedName());
                        userAction.setBrandTasteId(brandTasteDTO.getBrandTasteId());
                        userAction.setProductName(brandTasteDTO.getProductName());
                        userAction.setTasteName(brandTasteDTO.getTasteName());
                        userAction.setBrandNo(brandTasteDTO.getBrandNo());
                        userAction.setModel(brandTasteDTO.getModel());
                        userAction.setCompositeScore(brandTasteDTO.getCompositeScore());
                        userAction.setStyle(brandTasteDTO.getStyle());
                        userAction.setCoverUrl(brandTasteDTO.getCoverUrl());
                        userAction.setLikesCount(brandTasteDTO.getLikesCount());
                        userAction.setHasOwnerLikes(brandTasteDTO.isHasOwnerLikes());
                        userAction.setCollectionCount(brandTasteDTO.getCollectionCount());
                        userAction.setEvaluationCount(brandTasteDTO.getEvaluationCount());
                        userAction.setHasOwnerCollection(brandTasteDTO.isHasOwnerCollection());
                        userAction.setAvatar(MapUtils.getString(userAvatarMap, brandTasteDTO.getCreatedBy(), ""));
                        userAction.setNickName(MapUtils.getString(userNickNameMap, brandTasteDTO.getCreatedBy(), ""));
                    });
        });
        return userActionStoreRespPage;
    }

    public IPage<? extends UserActionListResp> getActionWithArticle(IPage<UserAction> userActionPage, Set<Long> objIds) {
        IPage<UserActionArticleResp> userActionStoreRespPage = userActionPage.convert(UserActionMapping.INSTANCE::coverToArticleResp);
        // 查询文章数据
        Integer tenantId = tenantFilterProperties.getTenantByBrand(SecurityUtils.getBrand());
        List<ArticleDTO> articleDTOList = articleService.getArticleByIds(new ArrayList<>(objIds), tenantId);
        if (CollUtil.isEmpty(articleDTOList)) {
            return userActionStoreRespPage;
        }
        // 用户行为数据
        articleActionDataManager.buildUserActionData(articleDTOList, SecurityUtils.getUserId());
        // 文章map
        Map<Long, ArticleDTO> articleMap =
                articleDTOList.stream().collect(Collectors.toMap(ArticleDTO::getArticleId, Function.identity(), (k1, k2) -> k1));
        List<UserActionArticleResp> records = userActionStoreRespPage.getRecords();
        for (UserActionArticleResp resp : records) {
            ArticleDTO articleDTO = MapUtils.getObject(articleMap, resp.getObjectId());
            if (Objects.isNull(articleDTO)) {
                continue;
            }
            dtoMapper(resp, articleDTO);
        }
        return userActionStoreRespPage;
    }

    private void dtoMapper(UserActionArticleResp resp, ArticleDTO articleDTO) {
        // 字段映射
        resp.setArticleId(articleDTO.getArticleId());
        resp.setArticleType(articleDTO.getArticleType());
        resp.setPublishTime(articleDTO.getPublishTime());
        resp.setArticleSite(articleDTO.getArticleSite());
        resp.setHasFollow(articleDTO.isHasFollow());
        resp.setAuditStatus(articleDTO.getAuditStatus());
        resp.setContentType(articleDTO.getContentType());
        resp.setCollectionCount(articleDTO.getCollectionCount());
        resp.setLikesCount(articleDTO.getLikesCount());
        resp.setHasOwnerCollection(articleDTO.isHasOwnerCollection());
        resp.setHasOwnerLikes(articleDTO.isHasOwnerLikes());
        resp.setCoverUrl(articleDTO.getCoverUrl());
        resp.setHeadline(articleDTO.getHeadline());
        resp.setEditType(articleDTO.getEditType());
        resp.setSource(articleDTO.getSource());
        resp.setParentCategory(articleDTO.getParentCategory());
        resp.setAttachmentList(articleDTO.getAttachmentList());
        resp.setEvaluationCount(articleDTO.getEvaluationCount());
        resp.setNickName(articleDTO.getNickName());
        resp.setAvatar(articleDTO.getAvatar());
        resp.setFansCount(articleDTO.getFansCount());
        resp.setHasFollow(articleDTO.isHasFollow());
        resp.setCreatedBy(articleDTO.getCreatedBy());
        resp.setCreatedName(articleDTO.getCreatedName());
        resp.setNickName(articleDTO.getNickName());
    }

    /**
     * 构建店铺的点赞统计及个人点赞数据
     *
     * @param userActionPage 分页数据
     * @param objIds         对象ID集合
     * @return
     */
    public IPage<UserActionStoreResp> getActionWithStore(IPage<UserAction> userActionPage, Set<Long> objIds) {
        IPage<UserActionStoreResp> userActionStoreRespPage = userActionPage.convert(UserActionMapping.INSTANCE::coverToStoreResp);
        // 查询店铺数据
        List<Store> stores = storeService.list(new LambdaQueryWrapper<Store>()
                .eq(Store::getDeletedVersion, 0L)
                .in(Store::getStoreId, objIds)
        );
        if (CollUtil.isEmpty(stores)) {
            return userActionStoreRespPage;
        }
        // 计算店铺距离
        List<AddressDTO> addressesList = addressCacheService.getAllAddressByCountry();
        userActionStoreRespPage.getRecords().forEach(userAction -> {
            stores.stream().filter(store1 -> store1.getStoreId().equals(userAction.getObjectId())).findFirst()
                    .ifPresent(store -> {
                        userAction.setStoreId(store.getStoreId());
                        userAction.setImageUrl(store.getImageUrl());
                        userAction.setStoreName(store.getStoreName());
                        userAction.setScore(store.getScore());
                        userAction.setAddress(store.getAddress());
                        userAction.setDistance(storeCacheService.calculateEntityDistance(store, userCacheService.getUserLocalInfo().getLongitude()
                                , userCacheService.getUserLocalInfo().getLatitude()
                        ));
                        userAction.setAddressObject(addressesList.stream().filter(item -> item.getAddressId().equals(store.getAddressId())).findFirst().orElse(null));
                    });
        });
        return userActionStoreRespPage;
    }

    public IPage<UserActionActivityResp> getActionWithActivity(IPage<UserAction> userActionPage, Set<Long> objIds) {
        IPage<UserActionActivityResp> userActionStoreRespPage = userActionPage.convert(UserActionMapping.INSTANCE::coverToActivityResp);
        // 查询活动列表数据
        List<Activity> activities = activityService.list(new LambdaQueryWrapper<Activity>()
                .eq(Activity::getDeletedVersion, 0L)
                .in(Activity::getActivityId, objIds)
        );
        if (CollUtil.isEmpty(activities)) {
            return userActionStoreRespPage;
        }
        // 查询预约数据
        List<ActivityReserve> activityReserves = reserveService.list(new LambdaQueryWrapper<ActivityReserve>()
                .eq(ActivityReserve::getDeletedVersion, 0L)
                .in(ActivityReserve::getActivityId, objIds)
                .eq(ActivityReserve::getCreatedBy, SecurityUtils.getUserId())
        );
        Map<Long, ActivityReserve> reserveMap = activityReserves.stream().collect(Collectors.toMap(ActivityReserve::getActivityId, Function.identity(), (k1, k2) -> k1));

        // 查询参与结果数据
        Map<Long, ActivityResult> activityResultMap = activityResultService.getAttendResult(new ArrayList<>(objIds));

        List<Long> objectIds = Lists.newArrayList();objectIds.addAll(objIds);
        Map<Long, List<AttachmentResp>> attachmentMap = attachmentService.getAttachmentByIds(objectIds);

        userActionStoreRespPage.getRecords().forEach(userAction -> {
            activities.stream().filter(store1 -> store1.getActivityId().equals(userAction.getObjectId())).findFirst()
                    .ifPresent(activity -> {
                        userAction.setActivityType(activity.getActivityType());
                        userAction.setHasOnline(activity.getHasOnline());
                        userAction.setActivityId(activity.getActivityId());
                        userAction.setPrizeName(activity.getPrizeName());
                        userAction.setPrizeBrand(activity.getPrizeBrand());
                        userAction.setPoints(activity.getPoints());
                        userAction.setCoverUrl(activity.getCoverUrl());
                        List<AttachmentResp> attachmentList = attachmentMap.get(activity.getActivityId());
                        if (CollUtil.isNotEmpty(attachmentList)) {
                            userAction.setCoverUrlList(attachmentList.stream().filter(attachmentResp -> attachmentResp.getHasCover() == 1).collect(Collectors.toList()));
                        }
                        /**
                         *   CASE
                         *         WHEN now() <![CDATA[ < ]]>  ct.start_time THEN 1
                         *         WHEN now() <![CDATA[ >= ]]> ct.start_time and now() <![CDATA[ < ]]> ct.end_time THEN  2
                         *         ELSE 3 END activityStatus,
                         */
                        // 计算活动状态
                        if (LocalDateTimeUtil.of(new Date()).compareTo(LocalDateTimeUtil.of(activity.getStartTime())) < 0) {
                            userAction.setActivityStatus(ActivityStatusEnum.RESERVE_ENABLE.getCode());
                        } else if (LocalDateTimeUtil.of(new Date()).compareTo(LocalDateTimeUtil.of(activity.getStartTime())) >= 0
                                && LocalDateTimeUtil.of(new Date()).compareTo(LocalDateTimeUtil.of(activity.getEndTime())) < 0) {
                            userAction.setActivityStatus(ActivityStatusEnum.IN_PROGRESS.getCode());
                        } else {
                            userAction.setActivityStatus(ActivityStatusEnum.OTHER.getCode());
                        }
                        userAction.setReserveStatus(0);
                        ActivityReserve activityReserve = MapUtils.getObject(reserveMap, activity.getActivityId());
                        if (Objects.nonNull(activityReserve)) {
                            userAction.setReserveStatus(activityReserve.getReserveStatus());
                        }
                        // 活动结果
                        userAction.setAttendResult(Objects.nonNull(MapUtils.getObject(activityResultMap, activity.getActivityId())));
                    });
        });
        return userActionStoreRespPage;
    }

    public IPage<UserActionEvaluateResp> getActionWithEvaluate(IPage<UserAction> userActionPage, Set<Long> objIds) {
        IPage<UserActionEvaluateResp> userActionStoreRespPage = userActionPage.convert(UserActionMapping.INSTANCE::coverToEvaluateResp);
        // 查询评价数据
        List<BrandTasteEvaluate> brandTasteEvaluates = evaluateService.list(new LambdaQueryWrapper<BrandTasteEvaluate>()
                .eq(BrandTasteEvaluate::getDeletedVersion, 0L)
                .in(BrandTasteEvaluate::getEvaluateId, objIds)
        );
        if (CollUtil.isEmpty(brandTasteEvaluates)) {
            return userActionStoreRespPage;
        }
        // 获取品牌信息
        List<BrandTasteDTO> brandTasteDTOS = brandTasteCacheService.getBrandTasteList(brandTasteEvaluates.stream().map(BrandTasteEvaluate::getBrandTasteId).collect(Collectors.toList()));
        // 获取附件
        Map<Long, List<AttachmentResp>> attachmentMap = attachmentService.getAttachmentByIds(brandTasteEvaluates.stream().map(BrandTasteEvaluate::getEvaluateId).collect(Collectors.toList()));
        // 获取评价管理数据：是否自己点赞，点赞统计，回复统计
        List<BrandTasteEvaluateDTO> targetResult = BrandTasteEvaluateMapping.INSTANCE.coverToDTOList(brandTasteEvaluates);
        buildEvaluateLikesData(targetResult);

        // 填充头像数据
        Map<Long, String> userAvatarMap = userCacheService.getMultiUserAvatar(targetResult.stream().map(BrandTasteEvaluateDTO::getCreatedBy).collect(Collectors.toList()));
        // 填充昵称
        Map<Long, String> userNickNameMap = userCacheService.getMultiUserNickName(targetResult.stream().map(BrandTasteEvaluateDTO::getCreatedBy).collect(Collectors.toList()));
        targetResult.forEach(item -> {
            item.setAvatar(MapUtils.getString(userAvatarMap, item.getCreatedBy(), ""));
            item.setNickName(MapUtils.getString(userNickNameMap, item.getCreatedBy(), ""));
        });

        userActionStoreRespPage.getRecords().forEach(userAction -> {
            targetResult.stream().filter(brandTasteEvaluate -> brandTasteEvaluate.getEvaluateId().equals(userAction.getObjectId())).findFirst()
                    .ifPresent(brandTasteDTO -> {
                        userAction.setBrandTasteId(brandTasteDTO.getBrandTasteId());
                        userAction.setEvaluateId(brandTasteDTO.getEvaluateId());
                        brandTasteDTOS.stream().filter(item -> item.getBrandTasteId().equals(brandTasteDTO.getBrandTasteId())).findFirst()
                                .ifPresent(brandTasteDTO1 -> {
                                    userAction.setModel(brandTasteDTO1.getModel());
                                    userAction.setTasteName(brandTasteDTO1.getTasteName());
                                    userAction.setBrandNo(brandTasteDTO1.getBrandNo());
                                    userAction.setStyle(brandTasteDTO1.getStyle());
                                });
                        userAction.setAttachmentList(attachmentMap.get(brandTasteDTO.getEvaluateId()));
                        userAction.setCompositeScore(brandTasteDTO.getCompositeScore());
                        userAction.setEvaluateContent(brandTasteDTO.getEvaluateContent());
                        userAction.setLikesCount(brandTasteDTO.getLikesCount());
                        userAction.setHasOwnerLikes(brandTasteDTO.isHasOwnerLikes());
                        userAction.setReplyCount(brandTasteDTO.getReplyCount());
                        userAction.setAvatar(brandTasteDTO.getAvatar());
                        userAction.setCreatedName(brandTasteDTO.getCreatedName());
                        userAction.setNickName(brandTasteDTO.getNickName());
                        userAction.setAvatar(brandTasteDTO.getAvatar());
                    });
        });
        return userActionStoreRespPage;
    }
}
